#include "frpc_msgio.h"
#include <cppbase/logging.h>


namespace frpc{
    //on bytes recied
int MsgIO::append(const void *buf, size_t *size)
{
    return parse_full_stream((char*)buf,size);

}

// to build bytes to send
int MsgIO::encode(struct iovec vectors[], int max)
{   

return collect_output(vectors);//number of string block
}



int MsgIO::get_compress_type() const
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	return meta.compress_type();
}

void MsgIO::set_compress_type(int type)
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	meta.set_compress_type(type);
}





const std::string& Request::get_service_name() const
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	return meta.request().service_name();
}

const std::string& Request::get_method_name() const
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	return meta.request().method_name();
}

void Request::set_service_name(const std::string& service_name)
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	meta.mutable_request()->set_service_name(service_name);
}

void Request::set_method_name(const std::string& method_name)
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	meta.mutable_request()->set_method_name(method_name);
}

int64_t Request::get_correlation_id() const
{
	//const BrpcMeta* meta = static_cast<const BrpcMeta*>(meta);

	if (meta.has_correlation_id())
		return meta.correlation_id();

	return -1;
}

void Request::set_correlation_id(uint64_t v)
{
	meta.set_correlation_id(v);
}

int Reply::get_status_code() const
{
	return this->srpc_status_code;
}

void Reply::set_status_code(int code)
{
	this->srpc_status_code = code;
	//if (code != RPCStatusOK)
	//	this->srpc_error_msg = this->get_errmsg();
}

int Reply::get_error() const
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	return meta.response().error_code();
}

const char* Reply::get_errmsg() const
{
	
	return "";
}

void Reply::set_error(int error)
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	meta.mutable_response()->set_error_code(error);
}

void Reply::set_correlation_id(int64_t cid)
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);

	meta.set_correlation_id(cid);
}

int MsgIO::serialize(const google::protobuf::Message* pb_msg)
{
	reserve_body_buf(pb_msg->ByteSizeLong());
	pb_msg->SerializeToArray(body_buf.iov_base, body_buf.iov_len);
	body_used = pb_msg->ByteSizeLong();

	return 0;
}

int MsgIO::deserialize(google::protobuf::Message* pb_msg)
{
	pb_msg->ParseFromArray(body_buf.iov_base, body_used);
	free(body_buf.iov_base);
	body_buf.iov_base = nullptr;
	body_buf.iov_len = 0;
	body_used = 0;
	return 0;
}

int MsgIO::compress()
{
	//BrpcMeta* meta = static_cast<BrpcMeta*>(meta);
	bool is_resp = !meta.has_request();
	auto type = CompressType( meta.compress_type());

	if (this->Msg::body_used == 0)
		return 0;

	if (type == CompressType::None)
		return 0;

	

	return 0;
}

int MsgIO::decompress()
{
	return 0;
}
}